#include <assert.h>
#include <fcntl.h>
#include <pthread.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <signal.h>
#include <string>
#include "het_chatgpt.h" 
#include <curl/curl.h>

#include "cJSON.h"
#include "het_ringbuf.h" 
#define OAUTH_ERR 401
#define LOGIN_ERR 12001005
static char clife_mac_buf[32]={"34:a6:ef:f1:1b:a0"};
static char clife_config_url_buf[256] = {"https://ipd.clife.cn"};
static char clife_cms_url_buf[256] = {"https://cms.clife.cn"};
static char clife_get_config_url_buf[256] = {"/v4/app/smart-product-mirror/config/getConfig"};
static char clife_get_token_url_buf[256] = {"/v4/app/smart-product-mirror/config/getToken"};
static char clife_config_token_buf[256]={""};


static char clife_agent_toolchat_url_buf[256] = {"/agent-sdk/v1/microApp/toolChat"};
static char clife_agent_streamchat_url_buf[256] = {"/agent-sdk/v1/microApp/chat"};
static char clife_agent_createsession_url_buf[256] = {"/agent-sdk/v1/session/createSession"};
static char clife_agent_deletesession_url_buf[256] = {"/agent-sdk/v1/session/deleteSession"};


static char clife_agent_token_buf[512]={""};
static int clife_agent_microToolAppId=230;
static int clife_agent_microStreamAppId=305;
static char clife_agent_chatSessionId_buf[128]={""};
static char clife_userBuf[128]={""};//用户ID


/**
 * @brief 设置userId
 */
void update_user_id(char * userId){
    if(userId){
        strncpy(clife_userBuf,userId,sizeof(clife_userBuf)-1);
        clife_userBuf[sizeof(clife_userBuf)-1] = '\0';
    }else{
        clife_userBuf[0] = '\0';
    }
}
/**
 * @brief 获取userId
 */
char *get_user_id(void){
    if(strlen(clife_userBuf) < 2){
        return clife_mac_buf;
    }
    return clife_userBuf;
}

/**
 * @brief 设置mac
 */
void update_clife_mac(char * mac){
    if(mac){
        strncpy(clife_mac_buf,mac,sizeof(clife_mac_buf)-1);
        clife_mac_buf[sizeof(clife_mac_buf)-1] = '\0';
        HET_LOGI("clife_mac_buf %s\r\n",clife_mac_buf);
    }
}

/**
 * @brief 设置配置url
 */
void update_clife_config_url(char * url){
    if(url){
        strncpy(clife_config_url_buf,url,sizeof(clife_config_url_buf)-1);
        clife_config_url_buf[sizeof(clife_config_url_buf)-1] = '\0';
    }
}

/**
 * @brief 设置智能体url
 */
void update_clife_agent_url(char * url){
    if(url){
        strncpy(clife_cms_url_buf,url,sizeof(clife_cms_url_buf)-1);
        clife_cms_url_buf[sizeof(clife_cms_url_buf)-1] = '\0';
    }
}

/**
 * @brief 设置配置token
 */
void update_clife_config_token(char * token){
    if(token){
        strncpy(clife_config_token_buf,token,sizeof(clife_config_token_buf)-1);
        clife_config_token_buf[sizeof(clife_config_token_buf)-1] = '\0';
    }
}
/**
 * @brief 设置智能体token
 */
void update_clife_agent_token(char * token){
    if(token){
        strncpy(clife_agent_token_buf,token,sizeof(clife_agent_token_buf)-1);
        clife_agent_token_buf[sizeof(clife_agent_token_buf)-1] = '\0';
    }
}
/**
 * @brief 设置智能体appid
 */
void update_clife_agent_appid(int id){
    if(id!=0){
        clife_agent_microToolAppId = id;
    }
}
/**
 * @brief 设置智能体appid
 */
void update_clife_agent_stream_appid(int id){
    if(id!=0){
        clife_agent_microStreamAppId = id;
    }
}
/**
 * @brief 设置智能体会话ID
 */
void update_clife_agent_sessionId(char * sessionId){
    if(sessionId){
        strncpy(clife_agent_chatSessionId_buf,sessionId,sizeof(clife_agent_chatSessionId_buf)-1);
        clife_agent_chatSessionId_buf[sizeof(clife_agent_chatSessionId_buf)-1] = '\0';
    }else{
        clife_agent_chatSessionId_buf[0] = '\0';
    }
}
/**
 * @brief 获取sessionId
 */
char *get_clife_agent_sessionId(void){
    if(strlen(clife_agent_chatSessionId_buf) < 2){
        return NULL;
    }
    return clife_agent_chatSessionId_buf;
}

static char clife_agent_buf[8192]={'\0'};
/**
 * @brief 获取智能体返回结果
 */
char * clife_agent_get(void){
    char * ret=NULL;
    pthread_mutex_lock(&curl_agent_lock);
    if(strlen(clife_agent_buf) > 1){
        ret = strdup(clife_agent_buf);
        HET_LOGI("get_agent_buf %d\r\n",ret);
    };
    pthread_mutex_unlock(&curl_agent_lock);
    return ret;
}
void clife_agent_clean(void){
    pthread_mutex_lock(&curl_agent_lock);
    HET_LOGI("clife_agent_clean\r\n");
    clife_agent_buf[0]='\0';
    pthread_mutex_unlock(&curl_agent_lock);
}
#if 0
struct curl_slist *headers = NULL;
MemoryStruct chunk;
CURL *curl_stream = NULL;
void process_response(const char *response) {
    cJSON *response_json = cJSON_Parse(response);
    if (response_json == NULL) {
        HET_LOGI("Error parsing JSON response\n");
        return;
    }

    cJSON *retSampleRate = cJSON_GetObjectItemCaseSensitive(response_json, "sampleRate");
    if (cJSON_IsNumber(retSampleRate)) {
        int ali_sampleRate = retSampleRate->valueint;
        printf("Sample Rate: %d\n", ali_sampleRate);
    }

    cJSON *retVolume = cJSON_GetObjectItemCaseSensitive(response_json, "volume");
    if (cJSON_IsNumber(retVolume)) {
        int ali_volume = retVolume->valueint;
        printf("Volume: %d\n", ali_volume);
    }

    cJSON *retSpeechRate = cJSON_GetObjectItemCaseSensitive(response_json, "speechRate");
    if (cJSON_IsNumber(retSpeechRate)) {
        int ali_speechRate = retSpeechRate->valueint;
        printf("Speech Rate: %d\n", ali_speechRate);
    }

    cJSON *retPitchRate = cJSON_GetObjectItemCaseSensitive(response_json, "pitchRate");
    if (cJSON_IsNumber(retPitchRate)) {
        int ali_pitchRate = retPitchRate->valueint;
        printf("Pitch Rate: %d\n", ali_pitchRate);
    }

    cJSON *retResultMap = cJSON_GetObjectItemCaseSensitive(response_json, "resultMap");
    if (cJSON_IsObject(retResultMap)) {
        cJSON *retAuthorization = cJSON_GetObjectItemCaseSensitive(retResultMap, "Authorization");
        if (cJSON_IsString(retAuthorization)) {
            char clife_agentTokenBuf[256];
            strncpy(clife_agentTokenBuf, retAuthorization->valuestring, sizeof(clife_agentTokenBuf));
            printf("Authorization: %s\n", clife_agentTokenBuf);
        }

        cJSON *retMicroAppId = cJSON_GetObjectItemCaseSensitive(retResultMap, "microAppId");
        if (cJSON_IsNumber(retMicroAppId)) {
            int microAppId = retMicroAppId->valueint;
            printf("Micro App ID: %d\n", microAppId);
        }
    }

    cJSON_Delete(response_json);
}


int openai_stream_init(char * openaiToken,char * openaiUrl){ 
    // 初始化libcurl
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl_stream = curl_easy_init();

    //m_mediaURL填ws接口地址如 ws://xxxx.xxxx.net:8080/BlService
    curl_easy_setopt(curl_stream, CURLOPT_URL, openaiUrl);

    // Set other options as needed (e.g. TLS/HTTPS options)
    curl_easy_setopt(curl_stream, CURLOPT_TIMEOUT_MS, 3000);
    
    // Perform a regular transfer with CONNECT_ONLY set to enable WebSocket mode
    //注意要使用websocket模式时这里要填2
    curl_easy_setopt(curl_stream, CURLOPT_CONNECT_ONLY, (long)2);
    
    CURLcode res;
    res = curl_easy_perform(curl_stream);
    if(res == CURLE_OK) {
        return 0;
    }
    else
    {
        curl_easy_cleanup(curl_stream);
        curl_stream = NULL;
        return -1;
    }
    return 0;
}

int openai_stream_deinit(void){ 
    if(curl_stream){
        // 清理cURL相关资源
        curl_easy_cleanup(curl_stream);
    }
    curl_global_cleanup();
    return 0;
}

int openaiPut(CURL *curl, const char *textStr) {
    char cmdBuf[256] = {0};
    snprintf(cmdBuf, sizeof(cmdBuf), "{	\"tags\": [{\"mac\": \"%s\"}]	}", textStr);
    
    size_t sended = 0;
    CURLcode  res = curl_ws_send(curl, cmdBuf, strlen(cmdBuf)+1,  &sended,0, CURLWS_TEXT);
    
	if (res == CURLE_OK)
	{
		size_t rlen;
		struct curl_ws_frame *meta;
		char buffer[2560]  = {0};
		CURLcode result = curl_ws_recv(curl, buffer, sizeof(buffer), &rlen, &meta);
		if (result == CURLE_OK)
		{
			printf("%s\n", buffer);            
		}
	}    
    else
    {
        //
    }
    return 0;
}
#endif
int find_substring(const char *str, const char *substring) {
    int i, j;
    for (i = 0; str[i] != '\0'; i++) {
        for (j = 0; substring[j] != '\0'; j++) {
            if (str[i + j] != substring[j]) {
                break;
            }
        }
        if (substring[j] == '\0') {
            return i; // 找到子字符串
        }
    }
    return -1; // 未找到子字符串
}
void req_speechSynthesizer(MemoryStruct *chunk,int autoGoto){
    if(chunk->size > 1){
        HET_LOGI("buffer:%s\r\n",chunk->data);
    }
    if(chunk->audioSize > 1){
        HET_LOGI("audio:%s\r\n",chunk->audioData);
        pthread_mutex_lock(&curl_agent_lock);
        memset(clife_agent_buf,0,sizeof(clife_agent_buf)); 
        strncpy(clife_agent_buf,chunk->audioData,strlen(chunk->audioData)>sizeof(clife_agent_buf)-1?sizeof(clife_agent_buf)-1:strlen(chunk->audioData));
        pthread_mutex_unlock(&curl_agent_lock);
        HET_LOGI("clife_agent_buf:%s\r\n",clife_agent_buf);
        if(autoGoto){
            HET_LOGI("start\r\n");
            int ret = speechSynthesizerPut(chunk->audioData, RK_NULL);
            if(ret != 0){
                HET_LOGE("fail %d\r\n", ret);
            }
        }
    }
    free(chunk->data);
    free(chunk->audioData);
    free(chunk);
}
/**
 * 流式返回字符数据
 */
size_t write_callback_string(void *ptr, size_t size, size_t nmemb, void *userdata) {
    size_t realsize = size * nmemb,bufLen;
    int ret = 0;
    if(realsize > strlen("data:") && ptr){
        // 使用cJSON解析返回的数据
        int index = find_substring(ptr,"{");
        if(index < 0 || index > 10){
            HET_LOGE("agent:data not find %d \r\n",index);
            ret = -1;
        }else{
            cJSON *response_json = cJSON_Parse(ptr+index);
            if (response_json == NULL) {
                HET_LOGE("agent:json not find\r\n");
                ret = -1;
            } else {
                cJSON *jsonErrCode = cJSON_GetObjectItemCaseSensitive(response_json, "errCode");
                cJSON *jsonFinish = cJSON_GetObjectItemCaseSensitive(response_json, "finish");
                if (cJSON_IsNumber(jsonErrCode) && jsonErrCode->valueint == 0) {
                    cJSON *jsonContent = cJSON_GetObjectItemCaseSensitive(response_json, "content");
                    if (cJSON_IsString(jsonContent) && (jsonContent->valuestring != NULL)) {
                        MemoryStruct *mem = (MemoryStruct *)userdata;
                        //HET_LOGD("userdata [%p]\r\n",userdata);
                        bufLen = strlen(jsonContent->valuestring);
                        if(bufLen > 0){
                            if( mem->audioData){
                                char *ptr_new = (char *)realloc(mem->audioData, mem->audioSize + bufLen);
                                if (ptr_new == NULL) {
                                    // 内存分配失败
                                    HET_LOGE("audioData Not enough memory (realloc returned NULL) %d\r\n",bufLen);
                                    mem->audioData = NULL;
                                    mem->audioSize = 0;
                                    ret = -4;
                                }else{
                                    mem->audioData = ptr_new;
                                    memcpy(mem->audioData + strlen(mem->audioData), jsonContent->valuestring,bufLen);
                                    //HET_LOGI("agent audioData :  %d -> %d\r\n", mem->audioSize, mem->audioSize + bufLen);
                                    //HET_LOGI("agent data : %s \r\n", ptr);
                                    mem->audioSize += bufLen;
                                    mem->audioData[mem->audioSize -1] = '\0';
                                }
                            }
                        }else{
                            ret = -7;
                        }
                    }
                    else if (cJSON_IsBool(jsonFinish) && (jsonFinish->valueint != NULL)){
                        if(jsonFinish->valueint){
                            MemoryStruct *mem = (MemoryStruct *)userdata;
                            char *ptr_new = realloc(mem->data, mem->size + realsize);
                            if (ptr_new == NULL) {
                                // 内存分配失败
                                HET_LOGE("data Not enough memory (realloc returned NULL)\r\n");
                                mem->data = NULL;
                                mem->size = 0;
                                ret = -4;
                            }else{
                                mem->data = ptr_new;
                                memcpy(mem->data + mem->size, ptr+index, realsize);
                                mem->size += realsize;
                                mem->data[mem->size] = 0;
                                //HET_LOGI("agent Response: %s\r\n", mem->data);
                            }
                        }
                    }
                    else{
                        HET_LOGE("agent:content not find\r\n");
                        ret = -2;
                    }
                }else{
                    if(jsonErrCode->valueint == OAUTH_ERR){
                        clife_config_token_buf[0]='\0';
                        clife_agent_token_buf[0]='\0';
                        in_oath = RK_FALSE;
                    }
                    HET_LOGE("agent:errCode not find\r\n");
                    ret = -3;
                }
            }   
        }
    }
    if(ret != 0){
        HET_LOGE("agent Response error !!!\r\n");
        char *tmp = (char *)malloc(realsize + 1);
        if (tmp) {
            memset(tmp, 0, realsize + 1);
            memcpy(tmp, ptr, realsize);
            tmp[realsize] = 0;
            HET_LOGE("agent Response data: %s\r\n", tmp);
            free(tmp);
        }
    }
    return realsize;
}
static char clife_url[512];
char *getClife_url(char *hostBuf,char *urlBuf){
    memset(clife_url,0,sizeof(clife_url));
    snprintf(clife_url,sizeof(clife_url)-1,"%s%s",hostBuf,urlBuf);
    return clife_url;
}
/**
 * 临时token D2A973101FE74734B695FC10553537CCFF7B593923065299
 */
int clifeMicroAppToolChat(const char *query, int mode,int autoGoto){
    int ret =-1;
    CURL *curl ;
    CURLcode res;
    char *file_data;
    cJSON *result = NULL;
    cJSON *response_json = NULL;
    cJSON *retResponse = NULL;
    if(!in_oath){
        HET_LOGE("on auth\r\n");
        return -3;
    }
    if(!query){
        HET_LOGE("on query\r\n");
        return -4;
    }
    MemoryStruct *chunk = (MemoryStruct *)malloc(sizeof(MemoryStruct));
    if(chunk){
        chunk->data = (char *)malloc(1);  // 初始内存分配
        chunk->data[0]='\0';
        chunk->size = 0;          // 没有数据
        chunk->audioData = (char *)malloc(1);  // 初始内存分配
        chunk->audioData[0]='\0';
        chunk->audioSize = 0;          // 没有数据
    }else{
        HET_LOGE("chunk malloc fail\r\n");
        return -1;
    }
    // 创建JSON请求体
    cJSON * json = cJSON_CreateObject();
    cJSON_AddStringToObject(json, "query", query);
    cJSON_AddNumberToObject(json, "microAppId", clife_agent_microToolAppId);

    if(mode)
        cJSON_AddNumberToObject(json, "mode", mode);
    file_data = cJSON_PrintUnformatted(json);
    cJSON_Delete(json);
    json = NULL;

    HET_LOGI("data %s\r\n", file_data);

    HET_LOGD("lock\r\n");
    pthread_mutex_lock(&curl_lock);
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
    
    in_query = RK_TRUE;
    if(curl) {
        // 设置目标URL
        curl_easy_setopt(curl, CURLOPT_URL, getClife_url(clife_cms_url_buf,clife_agent_toolchat_url_buf));
        
        HET_LOGI("curl: %s\r\n", getClife_url(clife_cms_url_buf,clife_agent_toolchat_url_buf));

        // 设置HTTP头部，请求Upgrade到WebSocket
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        char accessTokenBuf[512];
        memset(accessTokenBuf, 0, sizeof(accessTokenBuf));
        snprintf(accessTokenBuf, sizeof(accessTokenBuf)-1, "Authorization: %s", clife_agent_token_buf);
        headers = curl_slist_append(headers, accessTokenBuf);
        
        HET_LOGI("accessTokenBuf %s\r\n", accessTokenBuf);
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        //临时禁用ssl
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
        //curl_easy_setopt(curl, CURLOPT_CAINFO,"/userdata/curl_cacert.pem");
 
        // 设置连接超时时间
        curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);
        // 设置POST请求
        curl_easy_setopt(curl, CURLOPT_HTTPPOST, 1L);

        // 设置请求体
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, file_data);
        // 设置回调函数处理响应
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback_string);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)chunk);

        // 执行请求
        ret = curl_easy_perform(curl);

        // 检查请求是否成功
        if(ret != CURLE_OK){
            HET_LOGE("failed: %s\r\n", curl_easy_strerror(res));
            ret =  -6;
        }
        // 清理cURL相关资源
        
        curl_slist_free_all(headers);
        curl_easy_cleanup(curl);
    }else{
        HET_LOGE("failed\r\n");
    }
    curl_global_cleanup();
    pthread_mutex_unlock(&curl_lock);
    HET_LOGI("unlock\r\n");
    // 清理JSON对象
    if(response_json){
        cJSON_Delete(response_json);
    }
    if(file_data)
        free(file_data);
    
    in_query = RK_FALSE;
    req_speechSynthesizer(chunk,autoGoto);
    return ret;
}


/**
 * 更新智能体token
 */
int clifeSmartProductMirrorGetconfig(void){
    int ret =-1;
    CURL *curl;
    CURLcode res;
    MemoryStruct chunk;
    cJSON *result = NULL;
    cJSON *response_json = NULL;

    chunk.data = (char *)malloc(1);  // 初始内存分配
    chunk.data[0]='\0';
    chunk.size = 0;          // 没有数据
    HET_LOGD("lock\r\n");
    pthread_mutex_lock(&curl_lock);

    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
    if(curl) {
        // 设置目标URL
        //curl_easy_setopt(curl, CURLOPT_URL, test_config_url_buf); 
        curl_easy_setopt(curl, CURLOPT_URL, getClife_url(clife_config_url_buf,clife_get_config_url_buf));
        
        HET_LOGI("curl: %s\r\n", getClife_url(clife_config_url_buf,clife_get_config_url_buf));

        // 设置HTTP头部，请求Upgrade到WebSocket
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/x-www-form-urlencoded");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        //临时禁用ssl
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
        //curl_easy_setopt(curl, CURLOPT_CAINFO,"/userdata/curl_cacert.pem");
 
        // 设置连接超时时间
        curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);
        // 设置POST请求
        curl_easy_setopt(curl, CURLOPT_HTTPPOST, 1L);

        // 设置请求体
        char postFields[256];
        //snprintf(postFields, sizeof(postFields), "accessToken=%s&physicalAddr=%s", clife_config_token_buf, clife_mac_buf);
        memset(postFields,0,256);
        snprintf(postFields, sizeof(postFields), "accessToken=%s", clife_config_token_buf);
        HET_LOGI("postFields: %s\r\n", postFields);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postFields);
        // 设置回调函数处理响应
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);

        // 执行请求
        ret = curl_easy_perform(curl);

        // 检查请求是否成功
        if(ret != CURLE_OK){
            HET_LOGE("failed: %s\r\n", curl_easy_strerror(res));
            ret = -6;
        }else{
            HET_LOGI("buffer:%s\r\n",chunk.data);
            // 使用cJSON解析返回的数据
            response_json = cJSON_Parse(chunk.data);
            if (response_json == NULL) {
                HET_LOGE("Error parsing JSON response\r\n");
                ret = -4;
            } else {
                cJSON *retCode = cJSON_GetObjectItemCaseSensitive(response_json, "code");
                if (cJSON_IsNumber(retCode) && retCode->valueint == 0) {
                    cJSON *retData = cJSON_GetObjectItemCaseSensitive(response_json, "data");
                    if (cJSON_IsObject(retData)) {
                        cJSON *retToken = cJSON_GetObjectItemCaseSensitive(retData, "token");
                        if (cJSON_IsString(retToken) ) {
                            HET_LOGI("ali_tokenBuf %s\r\n",retToken->valuestring);
                            update_ali_token(retToken->valuestring);
                        }
                        cJSON *retExpireTime = cJSON_GetObjectItemCaseSensitive(retData, "expireTime");
                        if (cJSON_IsNumber(retExpireTime) ) {
                            HET_LOGI("retExpireTime %d\r\n",retExpireTime->valueint);
                            update_ali_expireTime(retExpireTime->valueint);
                        }
                        cJSON *retAppkey = cJSON_GetObjectItemCaseSensitive(retData, "appkey");
                        if (cJSON_IsString(retAppkey) ) {
                            HET_LOGI("ali_appKeyBuf %s\r\n",retAppkey->valuestring);
                            update_ali_appKey(retAppkey->valuestring);
                        }
                        cJSON *retVoice = cJSON_GetObjectItemCaseSensitive(retData, "voice");
                        if (cJSON_IsString(retVoice) ) {
                            HET_LOGI("retVoice %s\r\n",retVoice->valuestring);
                            update_ali_voice(retVoice->valuestring);
                        }
                        cJSON *retSampleRate = cJSON_GetObjectItemCaseSensitive(retData, "sampleRate");
                        if (cJSON_IsNumber(retSampleRate) ) {
                            HET_LOGI("ali_sampleRate %d\r\n",retSampleRate->valueint);
                            update_ali_sampleRate(retSampleRate->valueint);
                        }else {
                            HET_LOGE("json parse ali_sampleRate error\r\n");
                            ret = -14;
                        }
                        cJSON *retVolume = cJSON_GetObjectItemCaseSensitive(retData, "volume");
                        if (retVolume && cJSON_IsNumber(retVolume) ) {
                            HET_LOGI("ali_volume %d\r\n",retVolume->valueint);
                            update_ali_volume(retVolume->valueint);
                        }else {
                            HET_LOGE("json parse retVolume error\r\n");
                            ret = -13;
                        }
                        cJSON *retSpeechRate = cJSON_GetObjectItemCaseSensitive(retData, "speechRate");
                        if (retSpeechRate && cJSON_IsNumber(retSpeechRate) ) {
                            HET_LOGI("ali_speechRate %d\r\n",retSpeechRate->valueint);
                            update_ali_speechRate(retSpeechRate->valueint);
                        }else {
                            HET_LOGE("json parse ali_speechRate error\r\n");
                            ret = -12;
                        }
                        cJSON *retPitchRate = cJSON_GetObjectItemCaseSensitive(retData, "pitchRate");
                        if (retPitchRate && cJSON_IsNumber(retPitchRate) ) {
                            HET_LOGI("ali_pitchRate %d\r\n",retPitchRate->valueint);
                            update_ali_pitchRate(retPitchRate->valueint);
                        }else {
                            HET_LOGE("json parse ali_pitchRate error\r\n");
                            ret = -11;
                        }
                        cJSON *retRresultMap = cJSON_GetObjectItemCaseSensitive(retData, "resultMap");
                        if (retRresultMap && cJSON_IsObject(retRresultMap) ) {
                            cJSON *retAuthorization = cJSON_GetObjectItemCaseSensitive(retRresultMap, "Authorization");
                            if (retAuthorization && cJSON_IsString(retAuthorization) ) {
                                HET_LOGI("clife_token %s\r\n",retAuthorization->valuestring);
                                update_clife_agent_token(retAuthorization->valuestring);
                                in_oath = RK_TRUE;
                            }else {
                                HET_LOGI("json parse Authorization error\r\n");
                                ret = -10;
                            }
                            cJSON *retMicroAppId = cJSON_GetObjectItemCaseSensitive(retRresultMap, "microAppId");
                            if (retMicroAppId && cJSON_IsNumber(retMicroAppId) ) {
                                HET_LOGI("clife_microAppId %d\r\n", retMicroAppId->valueint);
                                update_clife_agent_appid(retMicroAppId->valueint);
                            }else {
                                HET_LOGE("json parse microAppId error\r\n");
                                ret = -9;
                            }
                        }else {
                            HET_LOGE("json parse resultMap error\r\n");
                            ret = -8;
                        }
                    }else {
                        HET_LOGE("json parse data error\r\n");
                        ret = -7;
                    }
                } else {
                    if(retCode->valueint == OAUTH_ERR || retCode->valueint == LOGIN_ERR){
                        clife_config_token_buf[0]='\0';
                        clife_agent_token_buf[0]='\0';
                        in_oath = RK_FALSE;
                    }
                    HET_LOGE("code is not 0\r\n");
                    HET_LOGE("failed: %s\r\n", chunk.data);
                    ret = -5;
                }
            }
        }
        // 清理cURL相关资源
        
        curl_slist_free_all(headers);
        curl_easy_cleanup(curl);
    }else{
        HET_LOGE("failed\r\n");
    }
    curl_global_cleanup();
    pthread_mutex_unlock(&curl_lock);
    HET_LOGI("unlock\r\n");
    // 清理JSON对象
    if(response_json){
        cJSON_Delete(response_json);
    }
    free(chunk.data);
    return ret;
}

/**
 * 更新智能体token
 */
int clifeSmartProductMirrorGetconfigStreamGetToken(void){
    int ret =-1;
    CURL *curl;
    CURLcode res;
    MemoryStruct chunk;
    cJSON *result = NULL;
    cJSON *response_json = NULL;

    chunk.data = malloc(1);  // 初始内存分配
    chunk.data[0]='\0';
    chunk.size = 0;          // 没有数据
    HET_LOGD("lock\r\n");
    pthread_mutex_lock(&curl_lock);

    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
    if(curl) {
        // 设置目标URL
        curl_easy_setopt(curl, CURLOPT_URL, getClife_url(clife_config_url_buf,clife_get_token_url_buf));
        HET_LOGI("curl: %s\r\n", getClife_url(clife_config_url_buf,clife_get_token_url_buf));
        //curl_easy_setopt(curl, CURLOPT_URL, "https://itest.clife.net/v4/app/smart-product-mirror/config/getToken");
        //HET_LOGI("curl: %s\r\n", "https://itest.clife.net/v4/app/smart-product-mirror/config/getToken");
        

        // 设置HTTP头部，请求Upgrade到WebSocket
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/x-www-form-urlencoded");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        //临时禁用ssl
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
        //curl_easy_setopt(curl, CURLOPT_CAINFO,"/userdata/curl_cacert.pem");
 
        // 设置连接超时时间
        curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);
        // 设置POST请求
        curl_easy_setopt(curl, CURLOPT_HTTPPOST, 1L);

        // 设置请求体
        char postFields[256];
        //snprintf(postFields, sizeof(postFields), "accessToken=%s&physicalAddr=%s", clife_config_token_buf, clife_mac_buf);
        memset(postFields,0,256);
        snprintf(postFields, sizeof(postFields), "accessToken=%s", clife_config_token_buf);
        HET_LOGI("postFields: %s\r\n", postFields);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postFields);
        // 设置回调函数处理响应
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);

        // 执行请求
        ret = curl_easy_perform(curl);

        // 检查请求是否成功
        if(ret != CURLE_OK){
            HET_LOGE("failed: %s\r\n", curl_easy_strerror(res));
            ret = -6;
        }else{
            HET_LOGD("buffer:%s\r\n",chunk.data);
            // 使用cJSON解析返回的数据
            response_json = cJSON_Parse(chunk.data);
            if (response_json == NULL) {
                HET_LOGE("Error parsing JSON response\r\n");
                ret = -4;
            } else {
                cJSON *retCode = cJSON_GetObjectItemCaseSensitive(response_json, "code");
                if (cJSON_IsNumber(retCode) && retCode->valueint == 0) {
                    cJSON *retData = cJSON_GetObjectItemCaseSensitive(response_json, "data");
                    if (cJSON_IsObject(retData)) {
                        cJSON *retToken = cJSON_GetObjectItemCaseSensitive(retData, "token");
                        if (cJSON_IsString(retToken) ) {
                            HET_LOGI("ali_tokenBuf %s\r\n",retToken->valuestring);
                            update_ali_token(retToken->valuestring);
                        }
                        cJSON *retExpireTime = cJSON_GetObjectItemCaseSensitive(retData, "expireTime");
                        if (cJSON_IsNumber(retExpireTime) ) {
                            HET_LOGI("retExpireTime %d\r\n",retExpireTime->valueint);
                            update_ali_expireTime(retExpireTime->valueint);
                        }
                        cJSON *retAppkey = cJSON_GetObjectItemCaseSensitive(retData, "appkey");
                        if (cJSON_IsString(retAppkey) ) {
                            HET_LOGI("ali_appKeyBuf %s\r\n",retAppkey->valuestring);
                            update_ali_appKey(retAppkey->valuestring);
                        }
                        cJSON *retVoice = cJSON_GetObjectItemCaseSensitive(retData, "voice");
                        if (cJSON_IsString(retVoice) ) {
                            HET_LOGI("retVoice %s\r\n",retVoice->valuestring);
                            update_ali_voice(retVoice->valuestring);
                        }
                        cJSON *retSampleRate = cJSON_GetObjectItemCaseSensitive(retData, "sampleRate");
                        if (cJSON_IsNumber(retSampleRate) ) {
                            HET_LOGI("ali_sampleRate %d\r\n",retSampleRate->valueint);
                            update_ali_sampleRate(retSampleRate->valueint);
                        }else {
                            HET_LOGI("json parse ali_sampleRate error\r\n");
                            ret = -14;
                        }
                        cJSON *retVolume = cJSON_GetObjectItemCaseSensitive(retData, "volume");
                        if (retVolume && cJSON_IsNumber(retVolume) ) {
                            HET_LOGI("ali_volume %d\r\n",retVolume->valueint);
                            update_ali_volume(retVolume->valueint);
                        }else {
                            HET_LOGI("json parse retVolume error\r\n");
                            ret = -13;
                        }
                        cJSON *retSpeechRate = cJSON_GetObjectItemCaseSensitive(retData, "speechRate");
                        if (retSpeechRate && cJSON_IsNumber(retSpeechRate) ) {
                            HET_LOGI("ali_speechRate %d\r\n",retSpeechRate->valueint);
                            update_ali_speechRate(retSpeechRate->valueint);
                        }else {
                            HET_LOGI("json parse ali_speechRate error\r\n");
                            ret = -12;
                        }
                        cJSON *retPitchRate = cJSON_GetObjectItemCaseSensitive(retData, "pitchRate");
                        if (retPitchRate && cJSON_IsNumber(retPitchRate) ) {
                            HET_LOGI("ali_pitchRate %d\r\n",retPitchRate->valueint);
                            update_ali_pitchRate(retPitchRate->valueint);
                        }else {
                            HET_LOGI("json parse ali_pitchRate error\r\n");
                            ret = -11;
                        }
                        cJSON *userIdjson = cJSON_GetObjectItemCaseSensitive(retData, "userId");
                        if (userIdjson && cJSON_IsString(userIdjson) ) {
                            HET_LOGI("userIdjson %d\r\n",userIdjson->valuestring);
                            update_user_id(userIdjson->valuestring);
                        }else {
                            HET_LOGI("json parse userId error\r\n");
                        }
                        cJSON *retRresultMap = cJSON_GetObjectItemCaseSensitive(retData, "resultMap");
                        if (retRresultMap && cJSON_IsObject(retRresultMap) ) {
                            cJSON *retAuthorization = cJSON_GetObjectItemCaseSensitive(retRresultMap, "Authorization");
                            if (retAuthorization && cJSON_IsString(retAuthorization) ) {
                                HET_LOGI("clife_token %s\r\n",retAuthorization->valuestring);
                                update_clife_agent_token(retAuthorization->valuestring);
                                in_oath = RK_TRUE;
                            }else {
                                HET_LOGI("json parse Authorization error\r\n");
                                ret = -10;
                            }
                            cJSON *retMicroAppId = cJSON_GetObjectItemCaseSensitive(retRresultMap, "microAppId");
                            if (retMicroAppId && cJSON_IsNumber(retMicroAppId) ) {
                                HET_LOGI("clife_microAppId %d\r\n", retMicroAppId->valueint);
                                update_clife_agent_stream_appid(retMicroAppId->valueint);
                            }else {
                                HET_LOGE("json parse microAppId error\r\n");
                                ret = -9;
                            }
                        }else {
                            HET_LOGE("json parse resultMap error\r\n");
                            ret = -8;
                        }
                    }else {
                        HET_LOGE("json parse data error\r\n");
                        ret = -7;
                    }
                } else {
                    if(retCode->valueint == OAUTH_ERR || retCode->valueint == LOGIN_ERR){
                        clife_config_token_buf[0]='\0';
                        clife_agent_token_buf[0]='\0';
                        in_oath = RK_FALSE;
                    }
                    HET_LOGE("code is not 0\r\n");
                    HET_LOGE("failed: %s\r\n", chunk.data);
                    ret = -5;
                }
            }
        }
        // 清理cURL相关资源
        
        curl_slist_free_all(headers);
        curl_easy_cleanup(curl);
    }else{
        HET_LOGE("failed\r\n");
    }
    curl_global_cleanup();
    pthread_mutex_unlock(&curl_lock);
    HET_LOGI("unlock\r\n");
    // 清理JSON对象
    if(response_json){
        cJSON_Delete(response_json);
    }
    free(chunk.data);
    return ret;
}

/**
 * 创建会话
 */
int clifeSmartProductMirrorCreateSession(void){
    int ret =-1;
    CURL *curl;
    CURLcode res;
    MemoryStruct chunk;
    char *file_data;
    cJSON *result = NULL;
    cJSON *response_json = NULL;

    chunk.data = (char *)malloc(1);  // 初始内存分配
    chunk.data[0]='\0';
    chunk.size = 0;          // 没有数据

    // 创建JSON请求体
    cJSON * json = cJSON_CreateObject();
    if(get_user_id())
        cJSON_AddStringToObject(json, "userId", get_user_id());
    cJSON_AddNumberToObject(json, "microAppId", clife_agent_microStreamAppId);
    file_data = cJSON_PrintUnformatted(json);
    cJSON_Delete(json);
    json = NULL;
    HET_LOGI("data %s\r\n", file_data);
    HET_LOGD("lock\r\n");
    pthread_mutex_lock(&curl_lock);
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
    if(curl) {
        // 设置目标URL
        curl_easy_setopt(curl, CURLOPT_URL,  getClife_url(clife_cms_url_buf,clife_agent_createsession_url_buf));
        HET_LOGI("curl: %s\r\n", getClife_url(clife_cms_url_buf,clife_agent_createsession_url_buf));
        
        // 设置HTTP头部，请求Upgrade到WebSocket
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        char accessTokenBuf[512];
        memset(accessTokenBuf, 0, sizeof(accessTokenBuf));
        snprintf(accessTokenBuf, sizeof(accessTokenBuf)-1, "Authorization: %s", clife_agent_token_buf);
        headers = curl_slist_append(headers, accessTokenBuf);
        
        HET_LOGI("accessTokenBuf %s\r\n", accessTokenBuf);
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        //临时禁用ssl
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
        //curl_easy_setopt(curl, CURLOPT_CAINFO,"/userdata/curl_cacert.pem");
 
        // 设置连接超时时间
        curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);
        // 设置POST请求
        curl_easy_setopt(curl, CURLOPT_HTTPPOST, 1L);

        

        // 设置请求体
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, file_data);
        // 设置回调函数处理响应
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);

        // 执行请求
        ret = curl_easy_perform(curl);

        // 检查请求是否成功
        if(ret != CURLE_OK){
            HET_LOGI("failed: %s\r\n", curl_easy_strerror(res));
            ret = -6;
        }else{
            HET_LOGI("buffer:%s\r\n",chunk.data);
            // 使用cJSON解析返回的数据
            response_json = cJSON_Parse(chunk.data);
            if (response_json == NULL) {
                HET_LOGI("Error parsing JSON response\r\n");
                ret = -4;
            } else {
                cJSON *retCode = cJSON_GetObjectItemCaseSensitive(response_json, "code");
                if (cJSON_IsNumber(retCode) && retCode->valueint == 0) {
                    cJSON *retData = cJSON_GetObjectItemCaseSensitive(response_json, "data");
                    if (cJSON_IsObject(retData)) {
                        cJSON *clifeSession = cJSON_GetObjectItemCaseSensitive(retData, "sessionId");
                        if (cJSON_IsString(clifeSession) ) {
                            HET_LOGI("clife_session %s\r\n",clifeSession->valuestring);
                            update_clife_agent_sessionId(clifeSession->valuestring);
                        }else {
                            HET_LOGI("json parse sessionId error\r\n");
                            ret = -8;
                        }
                    }else {
                        HET_LOGI("json parse data error\r\n");
                        ret = -7;
                    }
                } else {
                    if(retCode->valueint == OAUTH_ERR || retCode->valueint == LOGIN_ERR){
                        clife_config_token_buf[0]='\0';
                        clife_agent_token_buf[0]='\0';
                        in_oath = RK_FALSE;
                    }
                    HET_LOGI("code is not 0\r\n");
                    HET_LOGI("failed: %s\r\n", chunk.data);
                    ret = -5;
                }
            }
        }
        // 清理cURL相关资源
        
        curl_slist_free_all(headers);
        curl_easy_cleanup(curl);
    }else{
        HET_LOGI("failed\r\n");
    }
    curl_global_cleanup();
    pthread_mutex_unlock(&curl_lock);
    HET_LOGI("unlock\r\n");
    // 清理JSON对象
    if(response_json){
        cJSON_Delete(response_json);
    }
    free(chunk.data);
    return ret;
}

/**
 * 创建会话
 */
int clifeSmartProductMirrorDeleteSession(char *ssesId){
    int ret =-1;
    CURL *curl;
    CURLcode res;
    MemoryStruct chunk;
    char *file_data;
    cJSON *result = NULL;
    cJSON *response_json = NULL;

    chunk.data = (char *)malloc(1);  // 初始内存分配
    chunk.data[0]='\0';
    chunk.size = 0;          // 没有数据

    // 创建JSON请求体
    cJSON * json = cJSON_CreateObject();
    cJSON_AddStringToObject(json, "sessionId", ssesId);
    file_data = cJSON_PrintUnformatted(json);
    cJSON_Delete(json);
    json = NULL;
    HET_LOGI("data %s\r\n", file_data);
    HET_LOGD("lock\r\n");
    pthread_mutex_lock(&curl_lock);
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
    if(curl) {
        // 设置目标URL
        curl_easy_setopt(curl, CURLOPT_URL,  getClife_url(clife_cms_url_buf,clife_agent_deletesession_url_buf));
        HET_LOGI("curl: %s\r\n", getClife_url(clife_cms_url_buf,clife_agent_deletesession_url_buf));
        
        // 设置HTTP头部，请求Upgrade到WebSocket
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        char accessTokenBuf[512];
        memset(accessTokenBuf, 0, sizeof(accessTokenBuf));
        snprintf(accessTokenBuf, sizeof(accessTokenBuf)-1, "Authorization: %s", clife_agent_token_buf);
        headers = curl_slist_append(headers, accessTokenBuf);
        
        HET_LOGI("accessTokenBuf %s\r\n", accessTokenBuf);
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        //临时禁用ssl
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
        //curl_easy_setopt(curl, CURLOPT_CAINFO,"/userdata/curl_cacert.pem");
 
        // 设置连接超时时间
        curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);
        // 设置POST请求
        curl_easy_setopt(curl, CURLOPT_HTTPPOST, 1L);

        

        // 设置请求体
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, file_data);
        // 设置回调函数处理响应
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);

        // 执行请求
        ret = curl_easy_perform(curl);

        // 检查请求是否成功
        if(ret != CURLE_OK){
            HET_LOGI("failed: %s\r\n", curl_easy_strerror(res));
            ret = -6;
        }else{
            HET_LOGI("buffer:%s\r\n",chunk.data);
            // 使用cJSON解析返回的数据
            response_json = cJSON_Parse(chunk.data);
            if (response_json == NULL) {
                HET_LOGI("Error parsing JSON response\r\n");
                ret = -4;
            } else {
                cJSON *retCode = cJSON_GetObjectItemCaseSensitive(response_json, "code");
                if (cJSON_IsNumber(retCode) && retCode->valueint == 0) {
                } else {
                    if(retCode->valueint == OAUTH_ERR || retCode->valueint == LOGIN_ERR){
                        clife_config_token_buf[0]='\0';
                        clife_agent_token_buf[0]='\0';
                        in_oath = RK_FALSE;
                    }
                    HET_LOGI("code is not 0\r\n");
                    HET_LOGI("failed: %s\r\n", chunk.data);
                    ret = -5;
                }
            }
        }
        // 清理cURL相关资源
        
        curl_slist_free_all(headers);
        curl_easy_cleanup(curl);
    }else{
        HET_LOGI("failed\r\n");
    }
    curl_global_cleanup();
    pthread_mutex_unlock(&curl_lock);
    HET_LOGI("unlock\r\n");
    // 清理JSON对象
    if(response_json){
        cJSON_Delete(response_json);
    }
    free(chunk.data);
    return ret;
}
/**
 * 填充参数
 */
int fillChatParam(cJSON * param){
    int ret =0,i;
	for(i = 0; i < 16; i++){
		if(g_personInfo.keys[i].name != NULL){
			cJSON_AddStringToObject(param, g_personInfo.keys[i].name, g_personInfo.keys[i].value);
            HET_LOGI("[%s][[%s]\r\n",g_personInfo.keys[i].name, g_personInfo.keys[i].value);
			ret =1;
		}
	}
    return ret;
}
/**
 * @brief 会话
 */
int clifeMicroAppChat(const char *query, int mode,int autoGoto){
    int ret =-1;
    CURL *curl ;
    CURLcode res;
    char *file_data;
    cJSON *result = NULL;
    cJSON *response_json = NULL;
    cJSON *retResponse = NULL;
    struct  person_key *personKey = NULL;
    if(!in_oath){
        HET_LOGE("on auth\r\n");
        return -3;
    }
    if(!query){
        HET_LOGE("on query\r\n");
        return -4;
    }
    MemoryStruct *chunk = (MemoryStruct *)malloc(sizeof(MemoryStruct));
    if(chunk){
        chunk->data = (char *)malloc(1);  // 初始内存分配
        chunk->data[0]='\0';
        chunk->size = 0;          // 没有数据
        chunk->audioData = (char *)malloc(1);  // 初始内存分配
        chunk->audioData[0]='\0';
        chunk->audioSize = 0;          // 没有数据
    }else{
        HET_LOGE("chunk malloc fail\r\n");
        return -1;
    }
    // 创建JSON请求体
    cJSON * json = cJSON_CreateObject();
    cJSON_AddStringToObject(json, "query", query);
    cJSON_AddNumberToObject(json, "microAppId", clife_agent_microStreamAppId);
    if(get_user_id())
        cJSON_AddStringToObject(json, "userId", get_user_id());
    if(get_clife_agent_sessionId())
        cJSON_AddStringToObject(json, "sessionId", get_clife_agent_sessionId());
    
    cJSON * param = cJSON_CreateObject();
    bool inParamFlag  = RK_FALSE;
    inParamFlag = fillChatParam(param);
    if(inParamFlag)
    {
        cJSON_AddItemToObject(json, "userParam", param);
    }else{
        cJSON_Delete(param);
        param = NULL;
    }

    if(mode)
        cJSON_AddNumberToObject(json, "mode", mode);
    file_data = cJSON_PrintUnformatted(json);
    cJSON_Delete(json);
    json = NULL;

    HET_LOGI("data %s\r\n", file_data);
    HET_LOGI("lock\r\n");
    pthread_mutex_lock(&curl_lock);
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
    
    in_query = RK_TRUE;
    if(curl) {
        // 设置目标URL
        curl_easy_setopt(curl, CURLOPT_URL, getClife_url(clife_cms_url_buf,clife_agent_streamchat_url_buf));
        HET_LOGI("curl: %s\r\n", getClife_url(clife_cms_url_buf,clife_agent_streamchat_url_buf));

        // 设置HTTP头部，请求Upgrade到WebSocket
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        char accessTokenBuf[512];
        memset(accessTokenBuf, 0, sizeof(accessTokenBuf));
        snprintf(accessTokenBuf, sizeof(accessTokenBuf)-1, "Authorization: %s", clife_agent_token_buf);
        headers = curl_slist_append(headers, accessTokenBuf);
        
        HET_LOGI("accessTokenBuf %s\r\n", accessTokenBuf);
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        //临时禁用ssl
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
        //curl_easy_setopt(curl, CURLOPT_CAINFO,"/userdata/curl_cacert.pem");
 
        // 设置连接超时时间
        curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);
        // 设置POST请求
        curl_easy_setopt(curl, CURLOPT_HTTPPOST, 1L);

        // 设置请求体
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, file_data);
        
        HET_LOGI("file_data: %s\r\n", file_data);
        // 设置回调函数处理响应
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback_string);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)chunk);

        // 执行请求
        ret = curl_easy_perform(curl);

        // 检查请求是否成功
        if(ret != CURLE_OK){
            HET_LOGI("failed: %s\r\n", curl_easy_strerror(res));
            ret =  -6;
        }
        // 清理cURL相关资源
        
        curl_slist_free_all(headers);
        curl_easy_cleanup(curl);
    }else{
        HET_LOGI("failed\r\n");
    }
    curl_global_cleanup();
    pthread_mutex_unlock(&curl_lock);
    HET_LOGI("unlock\r\n");
    // 清理JSON对象
    if(response_json){
        cJSON_Delete(response_json);
    }

    if(file_data){
        free(file_data);
    }
    
    in_query = RK_FALSE;
    req_speechSynthesizer(chunk,autoGoto);
    return ret;
}

